package com.example.paging3samples.ui

import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.WindowManager
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.paging3samples.R
import com.example.paging3samples.network.CustomResult
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private val mainViewModel: MainViewModel by viewModels()

    @Inject
    lateinit var mainAdapter: MainAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.decorView.systemUiVisibility =
            (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = Color.TRANSPARENT



        setContentView(R.layout.activity_main)
        viewModelConnections()
//        mainViewModel.getReposFromGitHub()

        val recyclerView: RecyclerView = findViewById(R.id.categories_recyclerView)
        recyclerView.adapter = mainAdapter
        lifecycleScope.launch {
            mainViewModel.getPosts().collectLatest {
                mainAdapter.submitData(it)
            }
        }
    }

    private fun viewModelConnections() {
        mainViewModel.observeData().observe(this) {
            when (it) {
                is CustomResult.Success -> {
                    "got into Success ${it.data}".print()
                }
                is CustomResult.Error.RecoverableError -> {
                    "got into RecoverableError ${it.exception}".print()
                }
                is CustomResult.Error.NonRecoverableError -> {
                    "got into NonRecoverableError ${it.exception}".print()
                }
                is CustomResult.Loading -> {
                    "got into Loading ${it.status}".print()
                }
            }
        }
    }
}

fun Any.print() {
    Log.v("PagingLogs ", " $this")
}